package com.sunshine.wrongquestionset.activity.login

import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat.getColor
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider

import com.google.android.material.snackbar.Snackbar

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.main.MainActivity
import com.sunshine.wrongquestionset.room.entity.AppConfigEntity
import es.dmoral.toasty.Toasty

import kotlinx.android.synthetic.main.fragment_login.*

class LoginFragment : Fragment() {

    private lateinit var viewModel: LoginViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_login, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)).get(LoginViewModel::class.java)

        forgetPassword()
        toRegister()

        to_login.setOnClickListener {
            val userId = edit_user_id.text?.toString()
            val password = edit_password.text?.toString()

            if (userId.isNullOrBlank() || userId.length > 20) {
                Snackbar.make(to_login, getString(R.string.user_id_error), Snackbar.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (password.isNullOrBlank() || password.length > 40) {
                Snackbar.make(to_login, getString(R.string.password_error), Snackbar.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            viewModel.toLogin(userId).observe(viewLifecycleOwner, Observer {
                //没有获取到账号信息或者密码错误
                if (it == null || it.password != password) {
                    Snackbar.make(to_login, getString(R.string.user_id_or_password_error), Snackbar.LENGTH_SHORT).show()
                }
                //登录允许
                else {
                    viewModel.updateAppConfig(userId, true)
                    Toasty.success(requireContext(), getString(R.string.login_success), Toasty.LENGTH_SHORT).show()
                    startActivity(Intent(requireActivity(), MainActivity::class.java))
                    requireActivity().finish()
                }
            })
        }
    }

    private fun forgetPassword() {
        val spannableString = SpannableString(getString(R.string.login_forget_password))
        spannableString.setSpan(UnderlineSpan(), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {

            }

        }, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        spannableString.setSpan(ForegroundColorSpan(getColor(requireContext(), R.color.color_primary)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        forget_password.apply {
            text = spannableString
            movementMethod = LinkMovementMethod.getInstance()
        }
    }

    private fun toRegister() {
        val spannableString = SpannableString(getString(R.string.login_to_register))
        spannableString.setSpan(UnderlineSpan(), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                activity?.supportFragmentManager?.beginTransaction()
                    ?.replace(R.id.login_root, RegisterFragment())
                    ?.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    ?.addToBackStack(null)
                    ?.commit()
            }

        }, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        spannableString.setSpan(ForegroundColorSpan(getColor(requireContext(), R.color.color_primary)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        to_register.apply {
            text = spannableString
            movementMethod = LinkMovementMethod.getInstance()
        }
    }
}